//
//  134. 加油站.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/7/21.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution134 {
    func canCompleteCircuit(_ gas: [Int], _ cost: [Int]) -> Int {
        var curSum = 0
        var totalSum = 0
        var start = 0
        for i in 0..<gas.count {
            curSum += gas[i] - cost[i]
            totalSum += gas[i] - cost[i]
            // 走不了，从下一个开始
            if curSum < 0 {
                start = i + 1
                curSum = 0
            }
        }
        if totalSum < 0 {
            return -1
        }
        return start
    }
    static func test() {
        //        let gas = [1,2,3,4,5]
        //        let cost = [3,4,5,1,2]
        //        let gas = [2,3,4]
        //        let cost = [3,4,3]
        let gas = [5,8,2,8]
        let cost = [6,5,6,6]
        let result = Solution134().canCompleteCircuit(gas, cost)
        print(result)
    }
}
